package com.opentool.web.db;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@Component("sqlliteConnection")
public class SqlliteConnection {

    private static final Logger logger = LoggerFactory.getLogger(SqlliteConnection.class);

    @Value("${server.sqllite.db.path}")
    private String dbPath;

    private Connection getConnection() throws Exception {
       Class.forName("org.sqlite.JDBC");
       Connection connection = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
       return connection;
    }

    public int execute(String sql) throws Exception {
        Connection connection=this.getConnection();
        Statement statement=connection.createStatement();
        int ret=statement.executeUpdate(sql);
        statement.close();
        connection.close();
        return ret;
    }


    public <T> List<T> executeQuery(String sql, RowMapper<T> rm) throws SQLException, ClassNotFoundException {
        List<T> rsList = new ArrayList<T>();
        Connection connection=null;
        Statement statement=null;
        try {
             connection=this.getConnection();
             statement=connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql);
             while (resultSet.next()) {
                rsList.add((T) rm.mapRow(resultSet, resultSet.getRow()));
             }
            return rsList;
        }catch (Exception e){
            logger.error(String.format("sql语句执行异常[%s]",sql),e);
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                }catch (Exception e){

                }
            }
            if(statement!=null){
                try {
                    statement.close();
                }catch (Exception e){

                }
            }
        }
        return null;
    }

}
